package other.xsy.pms;

import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.data.model.Account;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.task.FutureTask;
import other.xsy.pms.utils.HCXObjectService;

import java.util.List;

/**
 * @Description: 定时执行同步失败的客户
 * @Author: 黎炎松
 * @Date: 2024/4/10 10:52
 */
public class AccountToPmsSchedule implements ScheduleJob, FutureTask {

    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "定时执行同步失败的客户 ==> ";

    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        logger.debug(LOGGER_MSG + " 开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(AccountToPmsSchedule.class, "");
            logger.info(LOGGER_MSG + "异步ID:" + messageId);
        } catch (Exception e) {
            logger.error(LOGGER_MSG + " ----- 发生异常：" + e.getMessage());
        }
    }

    @Override
    public void execute(String s) throws ScriptBusinessException {
        dealSyncErrorAccount();
    }


    public static void main(String[] args) throws Exception {
        dealSyncErrorAccount();
    }


    /**
     * 处理同步失败的客户
     */
    public static void dealSyncErrorAccount() {
        try {
            // 查询同步失败的客户
            String sql = "select id,SyncStatus__c,syncCount__c from account where SyncStatus__c = 3 and (syncCount__c < 4 or syncCount__c is null)";
            List<? extends XObject> xObjects = hcxObjectService.queryAll(sql);
            if (xObjects.size() <= 0) {
                logger.debug(LOGGER_MSG + " 无需要同步的客户");
                return;
            }

            AccountToPmsTrigger accountToPmsTrigger = new AccountToPmsTrigger();
            // 重新执行
            for (XObject v : xObjects) {
                Account account = new Account();
                account.setId(v.getId());
                account = hcxObjectService.get(account);
                accountToPmsTrigger.handler(account);
            }
        } catch (Exception e) {
            logger.debug(LOGGER_MSG + " 同步异常: " + e.getMessage());
        }
    }

}
